package constant;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import freemarker.cache.FileTemplateLoader;
import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;

public class FreeMarkerConfig {

    public static Configuration configuration = new Configuration();

    static {
        try {
            String ftlPath = Constant.modelFiles;
            ftlPath = URLDecoder.decode(ftlPath, "utf-8");
            File file = new File(ftlPath);

            if (!file.exists()) {
                file.mkdir();
            }

            MultiTemplateLoader multiTemplateLoader = setFtlFloder(file);
            configuration.setTemplateLoader(multiTemplateLoader);
            configuration.setDefaultEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置ftl模板
     *
     * @param file
     * @throws IOException
     */
    private static MultiTemplateLoader setFtlFloder(File file) throws IOException {

        List<TemplateLoader> templateLoaders = new ArrayList<>();

        for (File currentFile : file.listFiles()) {
            if (currentFile.isDirectory()) {
                FileTemplateLoader fileTemplateLoader = new FileTemplateLoader(currentFile);
                templateLoaders.add(fileTemplateLoader);
            }
        }
        return new MultiTemplateLoader(templateLoaders.toArray(new TemplateLoader[templateLoaders.size()]));
    }

}
